package com.cloud.Service.impl;

import com.cloud.Service.UserInfoService;
import com.cloud.dao.UserInfoDao;
import com.cloud.domain.LoginUser;
import com.cloud.pojo.UserInfo;
import com.cloud.utils.JwtUtil;
import com.cloud.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author: Tangtao
 * @Date: 2022/4/11 13:00
 * @Description:  User information service layer implementation class
 * @ClassName: UserInfoServiceImpl
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Resource
    private UserInfoDao userInfoDao;

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisCache redisCache;

    @Override
    public boolean register(UserInfo userInfo) {
        return userInfoDao.register(userInfo) == 1;
    }


    @Override
    public Map<String, String>  loginByCardId(Map<String,String> mapData) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(mapData.get("userId")).setPassword(mapData.get("password"));
//        return userInfoDao.loginByPhoneNumber(userInfo) == 1;
        System.out.println(mapData.get("userId"));
        System.out.println(mapData.get("password"));
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userInfo.getUserId(),userInfo.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果认证没通过，给出对应的提示
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }
        //如果认证通过了，使用userid生成一个jwt jwt存入ResponseResult返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userid = loginUser.getUser().getUserId();
        String jwt = JwtUtil.createJWT(userid);
        Map<String,String> map = new HashMap<>();
        map.put("token",jwt);
        //把完整的用户信息存入redis  userid作为key
        redisCache.setCacheObject("login:"+userid,loginUser);
        map.put("name",loginUser.getUser().getName());
        map.put("type",loginUser.getUser().getType());
        map.put("userId",loginUser.getUser().getUserId());
        return map;
    }

    @Override
    public Map<String, String> loginByPhoneNumber(Map<String,String> mapData) {
        UserInfo userInfo = new UserInfo();
        System.out.println(mapData.toString());
        userInfo.setPhoneNumber(mapData.get("phoneNumber")).setPassword(mapData.get("password"));
//        return userInfoDao.loginByPhoneNumber(userInfo) == 1;

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userInfo.getPhoneNumber(),userInfo.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果认证没通过，给出对应的提示
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }
        //如果认证通过了，使用userid生成一个jwt jwt存入ResponseResult返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userid = loginUser.getUser().getUserId();
        String jwt = JwtUtil.createJWT(userid);
        Map<String,String> map = new HashMap<>();
        map.put("token",jwt);
        //把完整的用户信息存入redis  userid作为key
        redisCache.setCacheObject("login:"+userid,loginUser);
        map.put("name",loginUser.getUser().getName());
        map.put("type",loginUser.getUser().getType());
        map.put("userId",loginUser.getUser().getUserId());

        return map; //

    }

    @Override
    public boolean updateUserInfo(Map<String,String> map) {
        String userid = getUserIdFromToken();
        UserInfo userInfo = new UserInfo();
        userInfo.setDefaultRegion(Integer.parseInt(map.get("defaultRegion")))
                .setPhoneNumber(map.get("phoneNumber"))
                .setUserId(userid);
        return userInfoDao.updateUserInfo(userInfo) == 1;
    }

    @Override
    public boolean updateUserType(Map<String,String> map) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(map.get("userId")).setType(map.get("newType"));
        return userInfoDao.updateUserType(userInfo) == 1;
    }

    @Override
    public Map<String, String> getInfo() {
//        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        String userId = loginUser.getUser().getUserId();
        String userId = getUserIdFromToken();
        UserInfo result = userInfoDao.getInfo(new UserInfo().setUserId(userId));
        System.out.println(result);
        Map<String,String> resMap = new HashMap<>();
        System.out.println(result.toString());
        resMap.put("name",result.getName());
        resMap.put("defaultRegion",String.valueOf(result.getDefaultRegion()));
        resMap.put("phoneNumber",result.getPhoneNumber());
        resMap.put("type",result.getType());
        resMap.put("address",result.getAddress());
        return resMap;
    }

    @Override
    public boolean updatePwd(Map<String, String> map) {
        String UserId = getUserIdFromToken();

        return userInfoDao.updatePwd(new UserInfo()
                .setPassword(map.get("newPwd"))
                .setUserId(UserId)) == 1;
    }

    @Override
    public List<UserInfo> getAllUserInfo() {
        return userInfoDao.getAllUserInfo();
    }

    @Override
    public boolean deleteUserInfo(Map<String,String> map) {
        UserInfo userInfo = new UserInfo().setUserId(map.get("userId"))
                .setPhoneNumber(map.get("phoneNumber"));
        if (userInfo.getUserId()!=null)
            return userInfoDao.deleteUserInfoById(userInfo)==1;
        else if(userInfo.getPhoneNumber()!=null)
            return userInfoDao.deleteUserInfoByNum(userInfo)==1;
        return false;
    }

    public static String getUserIdFromToken(){
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return loginUser.getUser().getUserId();
    }
}
